package com.shycloud.mido.member.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shycloud.mido.member.api.entity.MemberOrder;
import com.shycloud.mido.member.api.vo.PayDepositVO;
import com.shycloud.mido.member.mapper.MemberOrderMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import lombok.AllArgsConstructor;

import java.util.List;

import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shycloud.mido.common.core.exception.BusinessException;
import com.shycloud.mido.common.core.util.R;
import com.shycloud.mido.member.api.entity.OrgBusiTypeDict;
import com.shycloud.mido.member.api.vo.StockDeviceInfoReqVO;
import com.shycloud.mido.member.api.vo.StockDeviceInfoRespVO;
import com.shycloud.mido.member.service.MemberActivateService;
import com.shycloud.mido.member.service.OrgBusiTypeDictService;
import com.shycloud.mido.member.service.StockDeviceInfoService;

/**
 * 代理商硬件管理
 *
 * @author nianhua.jiang and qiang.bai
 */
@RestController
@AllArgsConstructor
@RequestMapping("/opt/device")
@Api(tags = "代理商硬件管理（激活码为UDID字段）")
public class OptMasterController {

	/** 硬件销售类型字典 */
	private final OrgBusiTypeDictService orgBusiTypeDictService;
	/** 硬件设备 */
	private final StockDeviceInfoService stockDeviceInfoService;
	/** 激活历史 */
	private final MemberActivateService memberActivateService;
	/** 订单模块 service */
	private final MemberOrderMapper memberOrderMapper;

	@ApiOperation("硬件销售类型字典")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "busiType", value = "业务类型(1销售2出租3体验)", paramType = "query", dataType = "string", required = true)
	})
	@GetMapping("/listBusiType")
	public R<List<OrgBusiTypeDict>> listBusiType(String busiType) {
		LambdaQueryWrapper<OrgBusiTypeDict> query = Wrappers.<OrgBusiTypeDict>lambdaQuery()
				.in(OrgBusiTypeDict::getBusiType, busiType).eq(OrgBusiTypeDict::getDelFlag, "0")
				.orderByAsc(OrgBusiTypeDict::getCreateTime);
		List<OrgBusiTypeDict> result = orgBusiTypeDictService.list(query);
		return new R<>(result);
	}

	@ApiOperation("首页-设备分页查询")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "current", value = "当前页", paramType = "query", dataType = "int", required = true),
			@ApiImplicitParam(name = "size", value = "每页显示条数", paramType = "query", dataType = "int", required = true),
			@ApiImplicitParam(name = "optId", value = "运营商ID", paramType = "query", dataType = "int"),
			@ApiImplicitParam(name = "orgId", value = "机构ID", paramType = "query", dataType = "int"),
			@ApiImplicitParam(name = "distId", value = "经销商ID", paramType = "query", dataType = "int"),
			@ApiImplicitParam(name = "activeStatus", value = "(1未激活2空闲中3体验中4租赁中5已销售)", paramType = "query", dataType = "string")
	})
	@GetMapping("/pageStockDeviceInfo")
	public R<IPage<StockDeviceInfoRespVO>> pageStockDeviceInfo(Long current, Long size,
			StockDeviceInfoReqVO vo) {

		Page<StockDeviceInfoRespVO> page = new Page<>(current, size);
		IPage<StockDeviceInfoRespVO> result = stockDeviceInfoService
				.pageStockDeviceInfoRespVO(page, vo);
		return new R<>(result);
	}

	@ApiOperation("查找设备")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "current", value = "当前页", paramType = "query", dataType = "int", required = true),
			@ApiImplicitParam(name = "size", value = "每页显示条数", paramType = "query", dataType = "int", required = true),
			@ApiImplicitParam(name = "udid", value = "设备ID", paramType = "query", dataType = "string"),
			@ApiImplicitParam(name = "optId", value = "运营商ID", paramType = "query", dataType = "int"),
			@ApiImplicitParam(name = "orgId", value = "机构ID", paramType = "query", dataType = "int"),
			@ApiImplicitParam(name = "distId", value = "经销商ID", paramType = "query", dataType = "int")
	})
	@GetMapping("/getStockDeviceInfo")
	public R<StockDeviceInfoRespVO> getStockDeviceInfo(Long current, Long size,
			StockDeviceInfoReqVO vo) {

		if (!ObjectUtils.anyNotNull(vo.getOptId(), vo.getOrgId(), vo.getDistId())) {
			throw new BusinessException("机构ID和运营商ID");
		}
		StockDeviceInfoRespVO result = stockDeviceInfoService.getStockDeviceInfo(current, size, vo);
		return new R<>(result);
	}

	@ApiOperation("设备详情")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "udid", value = "设备ID", paramType = "query", dataType = "string"),
			@ApiImplicitParam(name = "optId", value = "运营商ID", paramType = "query", dataType = "int"),
			@ApiImplicitParam(name = "orgId", value = "机构ID", paramType = "query", dataType = "int"),
			@ApiImplicitParam(name = "distId", value = "经销商ID", paramType = "query", dataType = "int")
	})
	@GetMapping("/getStockDeviceDetail")
	public R<StockDeviceInfoRespVO> getStockDeviceDetail(StockDeviceInfoReqVO vo) {
		if (!ObjectUtils.anyNotNull(vo.getOptId(), vo.getOrgId(), vo.getDistId())) {
			throw new BusinessException("机构ID和运营商ID和经销商ID");
		}
		StockDeviceInfoRespVO result = stockDeviceInfoService.getStockDeviceDetail(vo);
		return new R<>(result);
	}


	@ApiOperation("是否体验过硬件")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "memberId", value = "用户ID", paramType = "query", dataType = "string", required = true),
	})
	@GetMapping("/existBusiType3ByMemberId")
	public R<Boolean> existBusiType3ByMemberId(String memberId) {
		Boolean result = memberActivateService.existBusiType3ByMemberId(memberId);
		return new R<>(result);
	}

	@ApiOperation("中止体验")
	@GetMapping("/stopExperience")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "udid", value = "设备码", paramType = "query", dataType = "string", required = true)
	})
	public R<Boolean> stopExperience(String udid) {
		return new R<>(stockDeviceInfoService.stopExperience(udid));
	}

	@GetMapping("getPayDepositCount")
	@ApiOperation("获取各个标签栏的数量")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "orgId", value = "机构ID", paramType = "query", dataType = "string", required = true)
	})
	public R getPayDepositCount(Integer orgId) {

		List<PayDepositVO> payDepositList = memberOrderMapper.getPayDepositList(orgId);
		//已缴费数量
		int okCount = payDepositList.stream().filter(x -> !"5".equals(x.getStatus()) && !"2".equals(x.getDevStatus())).collect(Collectors.toList()).size();
		//已过期数量
		int outTimeCount = payDepositList.stream().filter(x -> "5".equals(x.getStatus())).collect(Collectors.toList()).size();
		//已停用数量
		int stopCount = payDepositList.stream().filter(x -> "2".equals(x.getDevStatus())).collect(Collectors.toList()).size();
		Map<String, Integer> resMap = new HashMap<>(4);
		resMap.put("payDepositNonCount", memberOrderMapper.getPayDepositNonCount(orgId, "1"));
		resMap.put("payDepositOkCount", okCount);
		resMap.put("payDepositOutTimeCount", outTimeCount);
		resMap.put("payDepositStopCount", stopCount);
		return new R(resMap);
	}

	@ApiImplicitParams({
			@ApiImplicitParam(name = "orgId", value = "机构ID", paramType = "query", dataType = "string", required = true)
	})
	@GetMapping("getPayDepositNonList")
	@ApiOperation("合作商机构获取未缴费列表")
	public R<List<PayDepositVO>> getPayDepositNonList(Integer orgId) {
		//通过 orgId 获取 sm_member_order 的订单信息即可
		List<PayDepositVO> payDepositNonList = memberOrderMapper.getPayDepositNonList(orgId, "1");
		return new R<>(payDepositNonList);
	}

	@ApiImplicitParams({
			@ApiImplicitParam(name = "orgId", value = "机构ID", paramType = "query", dataType = "string", required = true)
	})
	@GetMapping("getPayDepositOkList")
	@ApiOperation("合作商机构获取已缴费列表")
	public R<List<PayDepositVO>> getPayDepositList(Integer orgId) {
		List<PayDepositVO> payDepositList = memberOrderMapper.getPayDepositList(orgId);
		//从已缴费列表中筛选已缴费（非【已过期】）人员
		List<PayDepositVO> res = payDepositList.stream().filter(x -> !"5".equals(x.getStatus()) && !"2".equals(x.getDevStatus()))
				.collect(Collectors.toList());

		//检索续费次数
		for (PayDepositVO payDepositVO : res) {
			Integer count = memberOrderMapper
					.selectCount(new QueryWrapper<MemberOrder>()
							.eq("status", "1")
							.and(x -> x.eq("order_type", 11).or().eq("order_type", 10))
							.eq("relation_order_no", payDepositVO.getOrderNoPerson()));
			payDepositVO.setPayTimes(count);
		}

		return new R<>(res);
	}

	@ApiImplicitParams({
			@ApiImplicitParam(name = "orgId", value = "机构ID", paramType = "query", dataType = "string", required = true)
	})
	@GetMapping("getPayOutTimeList")
	@ApiOperation("合作商机构获取已到期列表")
	public R<List<PayDepositVO>> getPayOutTimeList(Integer orgId) {
		List<PayDepositVO> payDepositList = memberOrderMapper.getPayDepositList(orgId);
		//从已缴费列表中筛选【已过期】人员
		List<PayDepositVO> res = payDepositList.stream().filter(x -> "5".equals(x.getStatus())).collect(Collectors.toList());

		//检索续费次数
		for (PayDepositVO payDepositVO : res) {
			Integer count = memberOrderMapper
					.selectCount(new QueryWrapper<MemberOrder>()
							.eq("status", "1")
							.and(x -> x.eq("order_type", 11).or().eq("order_type", 10))
							.eq("relation_order_no", payDepositVO.getOrderNoPerson()));
			payDepositVO.setPayTimes(count);
		}

		return new R<>(res);
	}

	@ApiImplicitParams({
			@ApiImplicitParam(name = "orgId", value = "机构ID", paramType = "query", dataType = "string", required = true)
	})
	@GetMapping("getPayStopList")
	@ApiOperation("合作商机构获取已停用列表")
	public R<List<PayDepositVO>> getPayStopList(Integer orgId) {
		//TODO udid 主表 status = 2 的场合为【已停用（作废）】
		List<PayDepositVO> payDepositList = memberOrderMapper.getPayDepositList(orgId);
		//从已缴费列表中筛选【已停用】人员
		List<PayDepositVO> res = payDepositList.stream().filter(x -> "2".equals(x.getDevStatus()))
				.collect(Collectors.toList());

		//检索续费次数
		for (PayDepositVO payDepositVO : res) {
			Integer count = memberOrderMapper
					.selectCount(new QueryWrapper<MemberOrder>()
							.eq("status", "1")
							.and(x -> x.eq("order_type", 11).or().eq("order_type", 10))
							.eq("relation_order_no", payDepositVO.getOrderNoPerson()));
			payDepositVO.setPayTimes(count);
		}

		return new R<>(res);
	}

	/**
	 * 租赁订单查询(小程序端)
	 *
	 * @param phone 查询的手机号
	 * @param orgId 机构 ID
	 * @return {@link R}
	 * @author nianhua.jiang
	 * @date 2021/11/9 9:21
	 */
	@GetMapping("getOrderByPhone")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "orgId", value = "机构ID", paramType = "query", dataType = "string", required = true),
			@ApiImplicitParam(name = "phone", value = "查询电话", paramType = "query", dataType = "string", required = true)
	})
	@ApiOperation("小程序端查询订单")
	public R getOrderByPhone(String phone, Integer orgId) {

		//先查询未缴费内容
		List<PayDepositVO> payDepositNonList = memberOrderMapper.getPayDepositNonList(orgId, "1");

		List<PayDepositVO> res = payDepositNonList.stream().filter(x -> phone.equals(x.getPhone())).collect(Collectors.toList());

		//次查询收货人的手机号
		List<PayDepositVO> payDepositList = memberOrderMapper.getPayDepositList(orgId);

		List<PayDepositVO> res2 = payDepositList.stream().filter(x -> phone.equals(x.getPhone())).collect(Collectors.toList());

		res.addAll(res2);

		//最后查询激活账号的手机号
		if (res == null || res.size() == 0) {
			res = payDepositList.stream().filter(x -> phone.equals(x.getActiveUsername())).collect(Collectors.toList());
		}

		for (PayDepositVO payDepositVO : res) {
			Integer count = memberOrderMapper
					.selectCount(new QueryWrapper<MemberOrder>()
							.eq("status", "1")
							.and(x -> x.eq("order_type", 11).or().eq("order_type", 10))
							.eq("relation_order_no", payDepositVO.getOrderNoPerson()));
			payDepositVO.setPayTimes(count);
		}

		return new R(res);
	}

}
